package com.liuyucheng.swing.timer;

import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 累计计时
 * @author LiuYuCheng
 * @date 2021年12月24日 16:49
 */
@Slf4j
public class Timer {

    private static boolean running;

    private static long startTime ;
    private static long endTime ;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日");
    private static SimpleDateFormat sdfMonth = new SimpleDateFormat("M月d日");
    public static SimpleDateFormat sdfSec = new SimpleDateFormat("yyyyMMddHHmmss");

    private static JLabel label2;
    private static JLabel label4;

    private static long leftSeconds = 60*60*1000;

    private static long selectSeconds = 60*60*1000;

    private static JLabel labelLeftTime;

    private static JProgressBar progressBar;

    public static void main(String[] args) throws Exception {
        try {
            //Win11
            //info.getName() = Metal
            //info.getName() = Nimbus
            //info.getName() = CDE/Motif
            //info.getName() = Windows
            //info.getName() = Windows Classic

//            MacOS
//            info.getName() = Metal
//            info.getName() = Nimbus
//            info.getName() = CDE/Motif
//            info.getName() = Mac OS X

            String osName = System.getProperty("os.name");
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Mac OS X".equals(info.getName()) && osName.contains("Mac")) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
                if ("Windows".equals(info.getName()) && osName.contains("Windows")) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | UnsupportedLookAndFeelException | IllegalAccessException | InstantiationException ex) {
            ex.printStackTrace();
        }

        TimeBean bean = ReadProperties.readInfo();

        JFrame frame = new JFrame("Steam");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(1000,300);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

        JPanel rootPanel = new JPanel();
        frame.setContentPane(rootPanel);
        rootPanel.setLayout(null);

        JButton buttonStart = new JButton("开始游戏");
        buttonStart.setBounds(0,0,200,50);
        buttonStart.setFont(new Font("微软雅黑",Font.PLAIN,18));
        rootPanel.add(buttonStart);

        JButton buttonEnd = new JButton("结束游戏...");
        buttonEnd.setBounds(0,0,200,50);
        buttonEnd.setFont(new Font("微软雅黑",Font.PLAIN,18));
        rootPanel.add(buttonEnd);
        buttonEnd.setVisible(false);

        buttonStart.addActionListener(e -> {
            startTime = System.currentTimeMillis();
            buttonStart.setVisible(false);
            buttonEnd.setVisible(true);

            running = true;
        });
        buttonEnd.addActionListener(e -> {
            running = false;

            TimeBean newBean = ReadProperties.readInfo();
            endTime = System.currentTimeMillis();
            leftSeconds = leftSeconds - (endTime - startTime);
            if(leftSeconds<=0){
                leftSeconds = 0;
            }
            buttonStart.setVisible(true);
            buttonEnd.setVisible(false);
            long gameTime = (endTime - startTime)/1000;
            System.out.println("秒数 = " + gameTime);
            long before = newBean.getTotalSeconds();
            long now = before + gameTime;
            ReadProperties.setProperties(now+"");

            label2.setText(getLastRunTime(new Date()));
            label4.setText(getGameTime(now));
        });

        JLabel label1 = new JLabel("最后运行日期");
        label1.setVerticalTextPosition(JLabel.CENTER);
        label1.setHorizontalTextPosition(JLabel.CENTER);
        label1.setHorizontalAlignment(JLabel.CENTER);
        label1.setFont(new Font("微软雅黑",Font.PLAIN,20));
        label1.setBounds(200,0,300,50);
        rootPanel.add(label1);

        label2 = new JLabel(getLastRunTime(sdfSec.parse(bean.getLastTime())));
        label2.setVerticalTextPosition(JLabel.CENTER);
        label2.setHorizontalTextPosition(JLabel.CENTER);
        label2.setHorizontalAlignment(JLabel.CENTER);
        label2.setFont(new Font("微软雅黑",Font.PLAIN,20));
        label2.setBounds(200,50,300,50);
        rootPanel.add(label2);

        JLabel label3 = new JLabel("游戏时间");
        label3.setVerticalTextPosition(JLabel.CENTER);
        label3.setHorizontalTextPosition(JLabel.CENTER);
        label3.setHorizontalAlignment(JLabel.CENTER);
        label3.setFont(new Font("微软雅黑",Font.PLAIN,20));
        label3.setBounds(500,0,300,50);
        rootPanel.add(label3);

        label4 = new JLabel(getGameTime(bean.getTotalSeconds()));
        label4.setVerticalTextPosition(JLabel.CENTER);
        label4.setHorizontalTextPosition(JLabel.CENTER);
        label4.setHorizontalAlignment(JLabel.CENTER);
        label4.setFont(new Font("微软雅黑",Font.PLAIN,20));
        label4.setBounds(500,50,300,50);
        rootPanel.add(label4);

        JButton stopButton = new JButton("退出");
        stopButton.setBounds(800,0,200,50);
        stopButton.setFont(new Font("微软雅黑",Font.PLAIN,18));
        rootPanel.add(stopButton);
        stopButton.addActionListener(e -> System.exit(0));

        JSeparator separator = new JSeparator();
        separator.setOrientation(JSeparator.HORIZONTAL);
        separator.setBounds(0,120,1000,1);
        rootPanel.add(separator);

        JLabel label5 = new JLabel("计时器");
        label5.setVerticalTextPosition(JLabel.CENTER);
        label5.setHorizontalTextPosition(JLabel.LEFT);
        label5.setHorizontalAlignment(JLabel.CENTER);
        label5.setFont(new Font("微软雅黑",Font.PLAIN,18));
        label5.setBounds(0,125,100,50);
        rootPanel.add(label5);

        JRadioButton radioButton1 = new JRadioButton("1小时");
        JRadioButton radioButton2 = new JRadioButton("1小时30分钟");
        JRadioButton radioButton3 = new JRadioButton("2小时");
        JRadioButton radioButton4 = new JRadioButton("2小时30分钟");
        JRadioButton radioButton5 = new JRadioButton("3小时");
        radioButton1.setName(String.valueOf(60*60*1000));
        radioButton2.setName(String.valueOf(60*90*1000));
        radioButton3.setName(String.valueOf(60*120*1000));
        radioButton4.setName(String.valueOf(60*150*1000));
        radioButton5.setName(String.valueOf(60*180*1000));
        ButtonGroup group = new ButtonGroup();
        group.add(radioButton1);
        group.add(radioButton2);
        group.add(radioButton3);
        group.add(radioButton4);
        group.add(radioButton5);
        radioButton1.setBounds(100,125,100,50);
        radioButton2.setBounds(200,125,150,50);
        radioButton3.setBounds(350,125,100,50);
        radioButton4.setBounds(450,125,150,50);
        radioButton5.setBounds(600,125,100,50);
        rootPanel.add(radioButton1);
        rootPanel.add(radioButton2);
        rootPanel.add(radioButton3);
        rootPanel.add(radioButton4);
        rootPanel.add(radioButton5);
        radioButton1.setSelected(true);
        ItemListener itemListener = new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getSource() instanceof JRadioButton){
                    JRadioButton radioButton = (JRadioButton) e.getSource();
                    if(radioButton.isSelected()){
                        String name = radioButton.getName();
                        leftSeconds = Long.parseLong(name);
                        selectSeconds = leftSeconds;
                        labelLeftTime.setText(secondToTime(leftSeconds));
                        labelLeftTime.repaint();
                    }
                }
            }
        };
        radioButton1.addItemListener(itemListener);
        radioButton2.addItemListener(itemListener);
        radioButton3.addItemListener(itemListener);
        radioButton4.addItemListener(itemListener);
        radioButton5.addItemListener(itemListener);

        JLabel label6 = new JLabel("剩余");
        label6.setVerticalTextPosition(JLabel.CENTER);
        label6.setHorizontalTextPosition(JLabel.LEFT);
        label6.setHorizontalAlignment(JLabel.CENTER);
        label6.setFont(new Font("微软雅黑",Font.PLAIN,18));
        label6.setBounds(0,175,100,50);
        rootPanel.add(label6);

        labelLeftTime = new JLabel(secondToTime(leftSeconds));
        labelLeftTime.setVerticalTextPosition(JLabel.CENTER);
        labelLeftTime.setHorizontalTextPosition(JLabel.LEFT);
        labelLeftTime.setHorizontalAlignment(JLabel.CENTER);
        labelLeftTime.setFont(new Font("微软雅黑",Font.PLAIN,24));
        labelLeftTime.setBounds(100,175,200,50);
        rootPanel.add(labelLeftTime);

        progressBar = new JProgressBar();
        progressBar.setIndeterminate(false);
        progressBar.setValue(0);
        progressBar.setStringPainted(false);
        progressBar.setBounds(0,240,1000,20);
        rootPanel.add(progressBar);

        rootPanel.repaint();

        new Thread(() -> {
            while (true){
                if(running){
                    long rightNow = System.currentTimeMillis();
                    long spent = rightNow - startTime; //ms
                    long leftTime = leftSeconds - spent;
                    labelLeftTime.setText(secondToTime(leftTime));
                    labelLeftTime.repaint();

                    BigDecimal kid = new BigDecimal(String.valueOf(selectSeconds - leftTime));
                    BigDecimal mother = new BigDecimal(String.valueOf(selectSeconds));
                    BigDecimal percent = kid.divide(mother,2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                    progressBar.setValue(percent.intValue());
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    /**
     * 展示最后运行日期
     * 日期间隔不到1天,展示今天
     * 间隔1天,展示昨天
     * 间隔2天,展示前天
     * 间隔3-6天,展示n天前
     * 间隔7天,展示一周前
     * 超过7天并且是同年的,超过7天不同年并且相隔只差一个月的,展示x月x号
     * 超过7天不同年并且相隔超过1个月的,展示x年x月x号
     */
    private static String getLastRunTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        Calendar thatCalendar = Calendar.getInstance();
        thatCalendar.setTime(date);

        long offset = 8*3600*1000L;
        //今天的日子
        long today = (System.currentTimeMillis()+offset)/(1000L*3600*24);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        //当天
        long thatDay = (date.getTime()+offset)/(1000L*3600*24);
        int thatYear = thatCalendar.get(Calendar.YEAR);
        int thatMonth = thatCalendar.get(Calendar.MONTH)+1;
        //天数差
        long margin = today - thatDay;

        if(margin<1){
            return "今天";
        }else if(margin==1){
            return "昨天";
        }else if(margin==2){
            return "前天";
        }else if(margin<=6){
            return margin + "天前";
        }else if(margin==7){
            return "一周前";
        }else if(year == thatYear || (year-thatYear==1&&month==1&&thatMonth==12)){
            return sdfMonth.format(date);
        }

        return sdf.format(date);
    }

    /**
     * 展示游戏时间
     * @param totalSeconds
     * @return
     */
    private static String getGameTime(long totalSeconds) {
        BigDecimal result = new BigDecimal(totalSeconds+"").divide(new BigDecimal("3600"),1, RoundingMode.HALF_UP);
        if(result.compareTo(new BigDecimal("1"))<0){
            result = new BigDecimal(totalSeconds+"").divide(new BigDecimal("60"),1, RoundingMode.HALF_UP);
            return result + " 分钟";
        }
        return result + " 小时";
    }

    public static String secondToTime(long second){
        second = second/1000;

        long days = second / 86400;            //转换天数
        second = second % 86400;            //剩余秒数
        long hours = second / 3600;            //转换小时
        second = second % 3600;                //剩余秒数
        long minutes = second /60;            //转换分钟
        second = second % 60;                //剩余秒数
        if(days>0){
            return days + "天" + hours + "小时" + minutes + "分" + second + "秒";
        }else if(hours>0){
            return hours + "小时" + minutes + "分" + second + "秒";
        }else if(minutes>0){
            return minutes + "分" + second + "秒";
        }else if(second>0){
            return second + "秒";
        }else{
            return "已完成";
        }
    }
}
